<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span class="page-title">{{ title }}</span>
          <div class="header-actions">
            <el-button type="primary" @click="submitForm" :loading="loading">
              保存
            </el-button>
            <el-button @click="cancel">取消</el-button>
          </div>
        </div>
      </template>

      <el-form ref="doctorRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="医生姓名" prop="doctorName">
              <el-input v-model="form.doctorName" placeholder="请输入医生姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职称" prop="title">
              <el-input v-model="form.title" placeholder="请输入职称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属机构" prop="hospitalId">
              <el-select
                  v-model="form.hospitalId"
                  placeholder="请选择所属机构"
                  clearable
                  filterable
                  style="width: 100%"
                  @change="handleHospitalChange"
              >
                <el-option
                    v-for="hospital in hospitalOptions"
                    :key="hospital.hospitalId"
                    :label="hospital.hospitalName"
                    :value="hospital.hospitalId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属科室" prop="departmentId">
              <div class="department-cascader">
                <el-select
                    v-model="selectedParentDepartmentId"
                    placeholder="请先选择一级科室"
                    clearable
                    filterable
                    style="width: 100%; margin-bottom: 10px;"
                    @change="handleParentDepartmentChange"
                >
                  <el-option
                      v-for="department in parentDepartmentOptions"
                      :key="department.departmentId"
                      :label="department.departmentName"
                      :value="department.departmentId"
                  />
                </el-select>
                <el-select
                    v-model="form.departmentId"
                    placeholder="请选择二级科室"
                    clearable
                    filterable
                    style="width: 100%"
                    :disabled="!selectedParentDepartmentId"
                >
                  <el-option
                      v-for="department in subDepartmentOptions"
                      :key="department.departmentId"
                      :label="department.departmentName"
                      :value="department.departmentId"
                  />
                </el-select>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="工作年限" prop="workYears">
              <el-input v-model="form.workYears" placeholder="请输入工作年限">
                <template #append>年</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="咨询费用" prop="consultationFee">
              <el-input v-model="form.consultationFee" placeholder="请输入咨询费用">
                <template #append>元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否名医" prop="isFamous">
              <el-radio-group v-model="form.isFamous">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio label="0">正常</el-radio>
                <el-radio label="1">停诊</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="医生头像" prop="avatar">
          <el-upload
              class="avatar-uploader"
              action="#"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :http-request="handleAvatarUpload"
          >
            <el-image
                v-if="form.avatar"
                :src="form.avatar"
                class="avatar"
                fit="cover"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="form-tip" v-if="avatarUploading">
            <el-icon class="is-loading"><Loading /></el-icon>
            头像上传中...
          </div>
          <div class="form-tip">
            支持格式：jpg、png、jpeg，大小不超过2MB
          </div>
          <div class="form-tip warning" v-if="form.avatar && form.avatar.startsWith('data:') && !form.doctorId">
            <el-icon><Warning /></el-icon>
            头像已选择但未上传，请在保存前点击头像区域完成上传
          </div>
        </el-form-item>

        <el-form-item label="擅长领域" prop="specialty">
          <el-input
              v-model="form.specialty"
              type="textarea"
              placeholder="请输入擅长领域"
              :rows="4"
          />
        </el-form-item>

        <el-form-item label="医生描述" prop="description">
          <el-input
              v-model="form.description"
              type="textarea"
              placeholder="请输入医生描述"
              :rows="4"
          />
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup name="DoctorEdit">
import { getDoctor, addDoctor, updateDoctor, uploadAvatar } from "@/api/medical/doctor"
import { listHospital } from "@/api/institution/hospital"
import { listDepartments } from "@/api/department/departments"
import { getHospitalWithDepartments } from "@/api/institution/hospital"
import { useRoute, useRouter, onBeforeRouteLeave } from 'vue-router'
import { Plus, Loading, Warning } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { onBeforeUnmount, watch } from 'vue'

const { proxy } = getCurrentInstance()
const route = useRoute()
const router = useRouter()

const loading = ref(false)
const title = ref("")

// 表单相关
const form = ref({
  doctorId: null,
  doctorName: null,
  hospitalId: null,
  hospitalName: null,
  departmentId: null,
  departmentName: null,
  avatar: null,
  title: null,
  specialty: null,
  description: null,
  workYears: null,
  isFamous: 0,
  consultationFee: null,
  status: "0"
})

// 下拉框选项
const hospitalOptions = ref([])
const parentDepartmentOptions = ref([])
const subDepartmentOptions = ref([])
const selectedParentDepartmentId = ref(null)
const allDepartments = ref([])

// 头像上传相关
const avatarUploading = ref(false)
const avatarFile = ref(null)

const rules = {
  doctorName: [
    { required: true, message: "医生姓名不能为空", trigger: "blur" }
  ],
  hospitalId: [
    { required: true, message: "所属机构不能为空", trigger: "change" }
  ],
  departmentId: [
    { required: true, message: "所属科室不能为空", trigger: "change" }
  ],
  title: [
    { required: true, message: "职称不能为空", trigger: "blur" }
  ]
}

/** 清空表单数据 */
function resetForm() {
  form.value = {
    doctorId: null,
    doctorName: null,
    hospitalId: null,
    hospitalName: null,
    departmentId: null,
    departmentName: null,
    avatar: null,
    title: null,
    specialty: null,
    description: null,
    workYears: null,
    isFamous: 0,
    consultationFee: null,
    status: "0"
  }

  // 清空科室选择相关数据
  selectedParentDepartmentId.value = null
  subDepartmentOptions.value = []
  avatarFile.value = null

  // 重置表单验证
  if (proxy.$refs["doctorRef"]) {
    proxy.$refs["doctorRef"].resetFields()
  }
}

/** 监听路由参数变化 */
watch(
    () => route.query.doctorId,
    (newDoctorId, oldDoctorId) => {
      if (newDoctorId && newDoctorId !== oldDoctorId) {
        // 医生ID发生变化，加载新医生的数据
        loadDoctorData(newDoctorId)
      } else if (!newDoctorId && oldDoctorId) {
        // 从修改切换到新增，清空表单
        title.value = "添加医生"
        resetForm()
      }
    }
)

/** 初始化 */
onMounted(() => {
  const doctorId = route.query.doctorId
  if (doctorId) {
    title.value = "修改医生"
    getDoctorData(doctorId)
  } else {
    title.value = "添加医生"
    // 确保新增时表单是干净的
    resetForm()
  }

  getHospitalList()
  getAllDepartments()
})

/** 加载医生数据（供watch调用） */
function loadDoctorData(doctorId) {
  title.value = "修改医生"
  getDoctorData(doctorId)
}

/** 获取医生数据 */
function getDoctorData(doctorId) {
  loading.value = true
  getDoctor(doctorId).then(response => {
    form.value = response.data
    loading.value = false

    if (form.value.hospitalId) {
      getDepartmentList(form.value.hospitalId)
    }

    // 设置科室级联
    if (form.value.departmentId) {
      const selectedSubDept = allDepartments.value.find(
          dept => dept.departmentId === form.value.departmentId
      )
      if (selectedSubDept && selectedSubDept.parentId) {
        selectedParentDepartmentId.value = selectedSubDept.parentId
        subDepartmentOptions.value = allDepartments.value.filter(
            dept => dept.parentId === selectedParentDepartmentId.value
        )
      }
    }
  }).catch(() => {
    loading.value = false
    proxy.$modal.msgError('获取医生数据失败')
  })
}

/** 获取机构列表 */
function getHospitalList() {
  listHospital({ pageSize: 1000 }).then(response => {
    hospitalOptions.value = response.rows
  })
}

/** 获取所有科室数据 */
function getAllDepartments() {
  listDepartments({ pageSize: 10000 }).then(response => {
    allDepartments.value = response.rows || []

    // 筛选一级科室
    let level1Departments = allDepartments.value.filter(dept =>
        dept.level === 1 || dept.level === '1'
    )

    if (level1Departments.length === 0) {
      level1Departments = allDepartments.value.filter(dept =>
          !dept.parentId || dept.parentId === 0 || dept.parentId === '0'
      )
    }

    parentDepartmentOptions.value = level1Departments
  })
}

/** 获取科室列表 */
function getDepartmentList(hospitalId) {
  if (!hospitalId) {
    return
  }

  getHospitalWithDepartments(hospitalId).then(response => {
    if (response.code === 200 && response.data && response.data.departments) {
      // 可以在这里处理机构特定的科室数据
    }
  })
}

/** 机构选择变化 */
function handleHospitalChange(hospitalId) {
  if (hospitalId) {
    const selectedHospital = hospitalOptions.value.find(h => h.hospitalId === hospitalId)
    if (selectedHospital) {
      form.value.hospitalName = selectedHospital.hospitalName
    }
  } else {
    form.value.hospitalName = null
  }

  form.value.departmentId = null
  selectedParentDepartmentId.value = null
  subDepartmentOptions.value = []
}

/** 一级科室选择变化 */
function handleParentDepartmentChange(parentId) {
  if (parentId) {
    subDepartmentOptions.value = allDepartments.value.filter(
        dept => dept.parentId === parentId
    )
  } else {
    subDepartmentOptions.value = []
  }
  form.value.departmentId = null
}

/** 头像上传前校验 */
function beforeAvatarUpload(file) {
  const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPGOrPNG) {
    ElMessage.error('头像只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
    return false
  }
  return true
}

/** 处理头像上传 */
function handleAvatarUpload(options) {
  const { file } = options
  avatarUploading.value = true
  avatarFile.value = file

  const reader = new FileReader()
  reader.onload = (e) => {
    form.value.avatar = e.target.result
    avatarUploading.value = false
    ElMessage.info('头像已选择，点击"保存"时将上传头像')
  }
  reader.readAsDataURL(file)
  return false
}

/** 上传头像到服务器 */
function uploadAvatarToServer() {
  if (!avatarFile.value) {
    return Promise.resolve(form.value.avatar)
  }

  avatarUploading.value = true
  const formData = new FormData()
  formData.append('file', avatarFile.value)
  formData.append('doctorId', form.value.doctorId ? form.value.doctorId.toString() : '0')

  return new Promise((resolve, reject) => {
    uploadAvatar(formData).then(response => {
      avatarUploading.value = false
      if (response.code === 200) {
        let avatarUrl = response.data || response.msg || response.url
        if (avatarUrl) {
          form.value.avatar = avatarUrl
          avatarFile.value = null
          ElMessage.success('头像上传成功')
          resolve(avatarUrl)
        } else {
          ElMessage.error('头像上传成功但未返回URL')
          reject(new Error('头像上传成功但未返回URL'))
        }
      } else {
        ElMessage.error(response.msg || '头像上传失败')
        reject(new Error(response.msg || '头像上传失败'))
      }
    }).catch(error => {
      avatarUploading.value = false
      ElMessage.error('头像上传失败: ' + (error.message || '未知错误'))
      reject(error)
    })
  })
}

/** 准备提交数据 */
function prepareSubmitData() {
  const submitData = { ...form.value }

  // 移除日期字段，由后端自动处理
  delete submitData.createTime
  delete submitData.updateTime

  // 清除Base64格式的头像数据
  if (submitData.avatar && submitData.avatar.startsWith('data:')) {
    submitData.avatar = null
  }

  // 设置机构名称
  if (submitData.hospitalId) {
    const selectedHospital = hospitalOptions.value.find(h => h.hospitalId === submitData.hospitalId)
    if (selectedHospital) {
      submitData.hospitalName = selectedHospital.hospitalName
    }
  }

  // 设置科室名称
  if (submitData.departmentId) {
    const selectedDepartment = allDepartments.value.find(d =>
        d.departmentId === submitData.departmentId
    )
    if (selectedDepartment) {
      submitData.departmentName = getFullDepartmentName(selectedDepartment)
    }
  }

  return submitData
}

/** 获取完整科室名称 */
function getFullDepartmentName(department) {
  if (!department) return ''

  if ((department.level === 2 || department.level === '2') && department.parentId) {
    const parentDept = allDepartments.value.find(d =>
        d.departmentId === department.parentId
    )
    if (parentDept) {
      return `${parentDept.departmentName}>${department.departmentName}`
    }
  }

  return department.departmentName || ''
}

/** 提交表单 */
async function submitForm() {
  proxy.$refs["doctorRef"].validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true

        // 上传头像
        if (avatarFile.value) {
          ElMessage.info('正在上传头像...')
          await uploadAvatarToServer()
        }

        // 准备提交数据
        const submitData = prepareSubmitData()

        if (form.value.doctorId) {
          await updateDoctor(submitData)
          proxy.$modal.msgSuccess("修改成功")
        } else {
          await addDoctor(submitData)
          proxy.$modal.msgSuccess("新增成功")
        }

        // 重要：通知父页面刷新数据
        if (window.opener && window.opener.getList) {
          window.opener.getList()
        } else {
          localStorage.setItem('doctorListShouldRefresh', Date.now().toString())
        }

        // 保存成功后直接返回列表页面
        router.push('/medical/doctor')

      } catch (error) {
        console.error('操作失败:', error)
        proxy.$modal.msgError("操作失败")
      } finally {
        loading.value = false
      }
    }
  })
}

/** 取消 */
function cancel() {
  router.push('/medical/doctor')
}

/** 路由离开守卫 */
onBeforeRouteLeave((to, from, next) => {
  // 离开编辑页面时清空数据
  resetForm()
  next()
})

/** 组件卸载时清空数据 */
onBeforeUnmount(() => {
  resetForm()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title {
  font-size: 18px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.department-cascader {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 10px;
  background: #f8f9fa;
}

.avatar-uploader {
  :deep(.el-upload) {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
    width: 120px;
    height: 120px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  :deep(.el-upload:hover) {
    border-color: var(--el-color-primary);
  }
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
  line-height: 120px;
}

.form-tip {
  font-size: 12px;
  color: #666;
  margin-top: 5px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.form-tip.warning {
  color: #e6a23c;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-card__header) {
  background: #f8f9fa;
  border-bottom: 1px solid #e4e7ed;
}
</style>